package org.jash.ting13.book

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.launch
import org.jash.ting13.entity.PlayUrl
import org.jash.ting13.net.APIService
import org.jash.utils.log
import org.jash.utils.mvi.BaseViewModel
import org.jash.utils.net.service

class BookViewModel : BaseViewModel<BookIntent, BookState>() {
    private val service: APIService = service()

    init {
        viewModelScope.launch {
            intent.consumeAsFlow().collect {
                when (it) {
                    is BookIntent.LoadDetail -> loadDetail(it.url)
                }
            }
        }
    }

    private suspend fun loadDetail(url: String) {
        Pager(PagingConfig(48)) {
            ChapterPagingSource(service, url)
        }.flow.cachedIn(viewModelScope).take(1).collect {
            this@BookViewModel.state.postValue(BookState.Paging(it))
        }
        val state = try {
            val bookDetail = service.getDetail(url, 1)
            BookState.Success(bookDetail)
        } catch (e: Exception) {
            BookState.Failure(e.message ?: "")
        }
        this.state.postValue(state)
    }

}